import random
import string
import sys

from PySide6.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QHBoxLayout,
                               QWidget, QLabel, QSpinBox, QLineEdit, QRadioButton,
                               QCheckBox, QPushButton, QTextEdit, QButtonGroup,
                               QGroupBox, QFileDialog, QMessageBox)

from licenseUtils import checkCode


class PasswordGenerator(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('账号密码生成器')
        self.setGeometry(100, 100, 800, 700)

        # 主窗口部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        layout = QVBoxLayout(main_widget)

        # 生成设置区域
        settings_group = QGroupBox('生成设置')
        settings_layout = QVBoxLayout(settings_group)

        # 生成数量
        count_layout = QHBoxLayout()
        count_layout.addWidget(QLabel('生成数量：'))
        self.count_spin = QSpinBox()
        self.count_spin.setRange(1, 100)
        self.count_spin.setValue(20)
        count_layout.addWidget(self.count_spin)
        count_layout.addStretch()
        settings_layout.addLayout(count_layout)

        # 账号前缀
        prefix_layout = QHBoxLayout()
        prefix_layout.addWidget(QLabel('账号前缀：'))
        self.prefix_edit = QLineEdit('user_')
        prefix_layout.addWidget(self.prefix_edit)
        prefix_layout.addStretch()
        settings_layout.addLayout(prefix_layout)

        # 账号类型
        account_type_layout = QHBoxLayout()
        account_type_layout.addWidget(QLabel('账号后缀：'))
        self.sequential_radio = QRadioButton('数字序列')
        self.random_radio = QRadioButton('随机字符串')
        self.sequential_radio.setChecked(True)
        account_type_layout.addWidget(self.sequential_radio)
        account_type_layout.addWidget(self.random_radio)
        account_type_layout.addStretch()
        settings_layout.addLayout(account_type_layout)

        # 账号长度
        account_length_layout = QHBoxLayout()
        account_length_layout.addWidget(QLabel('账号长度：'))
        self.account_length_spin = QSpinBox()
        self.account_length_spin.setRange(1, 50)
        self.account_length_spin.setValue(6)
        account_length_layout.addWidget(self.account_length_spin)
        account_length_layout.addStretch()
        settings_layout.addLayout(account_length_layout)

        # 密码长度
        password_length_layout = QHBoxLayout()
        password_length_layout.addWidget(QLabel('密码长度：'))
        self.password_length_spin = QSpinBox()
        self.password_length_spin.setRange(1, 50)
        self.password_length_spin.setValue(12)
        password_length_layout.addWidget(self.password_length_spin)
        password_length_layout.addStretch()
        settings_layout.addLayout(password_length_layout)

        # 密码包含字符类型
        chars_group = QGroupBox('密码包含：')
        chars_layout = QVBoxLayout(chars_group)

        self.upper_check = QCheckBox('大写字母（A-Z）')
        self.upper_check.setChecked(True)
        self.lower_check = QCheckBox('小写字母（a-z）')
        self.lower_check.setChecked(True)
        self.digit_check = QCheckBox('数字（0-9）')
        self.digit_check.setChecked(True)
        self.special_check = QCheckBox('特殊字符（!@#$%等）')
        self.special_check.setChecked(True)

        chars_layout.addWidget(self.upper_check)
        chars_layout.addWidget(self.lower_check)
        chars_layout.addWidget(self.digit_check)
        chars_layout.addWidget(self.special_check)

        # 自定义特殊字符
        custom_special_layout = QHBoxLayout()
        custom_special_layout.addWidget(QLabel('自定义特殊字符：'))
        self.custom_special_edit = QLineEdit('@#$%^&*')
        custom_special_layout.addWidget(self.custom_special_edit)
        chars_layout.addLayout(custom_special_layout)

        settings_layout.addWidget(chars_group)

        # 生成按钮
        self.generate_btn = QPushButton('生成账号密码')
        self.generate_btn.clicked.connect(self.generate_accounts)
        settings_layout.addWidget(self.generate_btn)

        layout.addWidget(settings_group)

        # 生成结果预览
        preview_group = QGroupBox('生成结果预览')
        preview_layout = QVBoxLayout(preview_group)
        self.preview_text = QTextEdit()
        self.preview_text.setMaximumHeight(200)
        preview_layout.addWidget(self.preview_text)
        layout.addWidget(preview_group)

        # 保存格式 - 使用按钮组确保单选
        save_format_layout = QHBoxLayout()
        save_format_layout.addWidget(QLabel('保存格式：'))

        # 创建按钮组
        self.save_format_group = QButtonGroup(self)

        self.txt_radio = QRadioButton('TXT文件')
        self.excel_radio = QRadioButton('Excel文件')
        self.txt_radio.setChecked(True)

        # 将单选按钮添加到按钮组
        self.save_format_group.addButton(self.txt_radio)
        self.save_format_group.addButton(self.excel_radio)

        save_format_layout.addWidget(self.txt_radio)
        save_format_layout.addWidget(self.excel_radio)
        save_format_layout.addStretch()
        layout.addLayout(save_format_layout)

        # 保存按钮
        self.save_btn = QPushButton('保存结果')
        self.save_btn.clicked.connect(self.save_results)
        layout.addWidget(self.save_btn)

        # 存储生成的结果
        self.generated_data = []

    def generate_accounts(self):
        count = self.count_spin.value()
        prefix = self.prefix_edit.text()
        account_length = self.account_length_spin.value()
        password_length = self.password_length_spin.value()

        # 构建密码字符集
        char_sets = []
        if self.upper_check.isChecked():
            char_sets.append(string.ascii_uppercase)
        if self.lower_check.isChecked():
            char_sets.append(string.ascii_lowercase)
        if self.digit_check.isChecked():
            char_sets.append(string.digits)
        if self.special_check.isChecked():
            custom_special = self.custom_special_edit.text()
            char_sets.append(custom_special if custom_special else '!@#$%^&*')

        if not char_sets:
            QMessageBox.warning(self, '警告', '请至少选择一种字符类型！')
            return

        all_chars = ''.join(char_sets)

        self.generated_data = []
        preview_text = ""

        for i in range(count):
            # 生成账号
            if self.sequential_radio.isChecked():
                # 数字序列
                account_suffix = str(i + 1).zfill(account_length)
                account = f"{prefix}{account_suffix}"
            else:
                # 随机字符串
                account_chars = string.ascii_letters + string.digits
                account_suffix = ''.join(random.choices(account_chars, k=account_length))
                account = f"{prefix}{account_suffix}"

            # 生成密码
            password = ''.join(random.choices(all_chars, k=password_length))

            self.generated_data.append((account, password))
            preview_text += f"{account}: {password}\n"

        self.preview_text.setPlainText(preview_text)

    def save_results(self):
        if not self.generated_data:
            QMessageBox.warning(self, '警告', '请先生成账号密码！')
            return

        if self.txt_radio.isChecked():
            self.save_as_txt()
        else:
            self.save_as_excel()

    def save_as_txt(self):
        file_path, _ = QFileDialog.getSaveFileName(
            self, '保存TXT文件', '', 'Text Files (*.txt)'
        )

        if file_path:
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    for account, password in self.generated_data:
                        f.write(f"{account}: {password}\n")
                QMessageBox.information(self, '成功', '文件保存成功！')
            except Exception as e:
                QMessageBox.critical(self, '错误', f'保存文件时出错：{str(e)}')

    def save_as_excel(self):
        file_path, _ = QFileDialog.getSaveFileName(
            self, '保存Excel文件', '', 'Excel Files (*.xlsx)'
        )

        if file_path:
            try:
                # 使用openpyxl创建Excel文件
                from openpyxl import Workbook

                wb = Workbook()
                ws = wb.active
                ws.title = "账号密码"

                # 添加表头
                ws['A1'] = '账号'
                ws['B1'] = '密码'

                # 添加数据
                for i, (account, password) in enumerate(self.generated_data, start=2):
                    ws[f'A{i}'] = account
                    ws[f'B{i}'] = password

                # 调整列宽
                ws.column_dimensions['A'].width = 20
                ws.column_dimensions['B'].width = 30

                wb.save(file_path)
                QMessageBox.information(self, '成功', '文件保存成功！')
            except ImportError:
                QMessageBox.critical(self, '错误', '未安装openpyxl库，无法保存Excel文件。\n请运行: pip install openpyxl')
            except Exception as e:
                QMessageBox.critical(self, '错误', f'保存文件时出错：{str(e)}')





if __name__ == '__main__':
    if checkCode():
        app = QApplication(sys.argv)
        window = PasswordGenerator()
        window.show()
        sys.exit(app.exec())